<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  type DataTableColumns,
  NSpace,
  NInput,
  NModal
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination } from '@/utils/http'
import type { carlistModel } from '@/api/office'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

//表格
const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    width: '15rem'
  },
  {
    title: '车辆名称',
    key: 'carName',
    width: '50rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '车牌号',
    key: 'licensePlate',
    width: '50rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '备注',
    key: 'remarks',
    width: '50rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '500rem'
        }
      }
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: '50rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    width: '30rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        { type: 'primary', quaternary: true, onClick: () => handleEdit(e) },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'warning',
          quaternary: true,
          color: useStore.color['delete'],
          onClick: () => handleDelete([e?.id])
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]

//筛选条件
const carName: any = ref()
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData(true)
  }
})

//新增
const handleAdd = () => {
  router.push({
    path: '/OA/Office/AddCar',
  })
}

const handleEdit = (val: any) => {
  router.push({
    path: '/OA/Office/EditCar',
    query: {
      id: val.id
    }
  })
}

//删除弹窗
const modalVisible = ref(false)
const modalId = ref()
const againDelete = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'carDelete',
    override: {
      data: modalId.value
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  modalVisible.value = false
  queryTableData(true)
}

const handleDelete = (val: any) => {
  modalId.value = val
  modalVisible.value = true
}

const handleBatchDelete = () => {
  modalVisible.value = true
  modalId.value = dataListSelections.value
}

//多选框勾选
type DataListSelectionsItem = {
  id: string
}
const dataListSelections: any = ref<DataListSelectionsItem[]>([])
function selectionChangeHandle(val: any) {
  dataListSelections.value = val
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  dataListSelections.value = []
  const [error, res] = await sendRequest<HttpResponsePagination<carlistModel[]>>({
    module: 'office',
    api: 'carList',
    override: {
      params: {
        carName: carName.value,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  const tmp: any = res.data
  tableData.value = tmp?.list
  paginationReactive.itemCount = tmp?.totalCount
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Office/carSetting') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NFormItem label="车辆名称:">
            <NInput v-model:value="carName" placeholder="输入车辆名称" clearable />
          </NFormItem>
          <NFormItem>
            <NButton type="primary" ghost @click="queryTableData(true)" :loading="tableLoading">
              查询
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton type="error" style="width: 115px" @click="handleBatchDelete"
            :disabled="dataListSelections.length ? false : true" ghost>
            删除选中
          </NButton>
          <NButton type="primary" style="width: 115px" @click="handleAdd">
            新增用车
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" :checked-row-keys="dataListSelections" @update:checked-row-keys="selectionChangeHandle" />
    </template>


    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againDelete" title="删除提醒">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
